package cn.stronglink.assetmanage.business.search.presenter;

import android.content.Context;
import android.os.Environment;
import android.os.Handler;
import android.util.Log;

import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;

import org.greenrobot.greendao.query.QueryBuilder;

import java.io.IOException;
import java.net.HttpURLConnection;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import cn.stronglink.assetmanage.business.search.view.ISearchView;
import cn.stronglink.assetmanage.dao.DaoManager;
import cn.stronglink.assetmanage.dao.SearchAssetDao;
import cn.stronglink.assetmanage.dao.SyncTypesDao;
import cn.stronglink.assetmanage.entity.Result;
import cn.stronglink.assetmanage.entity.Room;
import cn.stronglink.assetmanage.entity.SearchAsset;
import cn.stronglink.assetmanage.entity.Status;
import cn.stronglink.assetmanage.entity.SyncTypes;
import cn.stronglink.assetmanage.entity.Type;
import cn.stronglink.assetmanage.utils.ImageUtils;
import cn.stronglink.netrequest.business.base.BaseDataService;
import cn.stronglink.netrequest.business.search.SearchService;
import cn.stronglink.netrequest.exceptions.BusinessErrorException;
import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.Response;

/**
 * Created by zhengjinglan on 2018/6/19.
 */

public class SearchListPresenter {
    private ISearchView searchView;
    private SearchService searchService;
    private Gson gson;
    private Context mContext;
    private Handler mHandler;
    private BaseDataService baseDataService;

    public SearchListPresenter(Context context, ISearchView searchView) {
        this.mContext = context;
        this.searchView = searchView;
        searchService = new SearchService();
        baseDataService = new BaseDataService();
        gson = new Gson();
        mHandler = new Handler();
    }





    public void queryAssetListFromLocal() {
        List<SearchAsset> searchAssetList = DaoManager.getDaoSession(mContext).getSearchAssetDao().loadAll();
        if (searchAssetList != null) {
            searchView.onSuccess(searchAssetList);
        }
    }

    // 保存数据到本地
    public void saveDataToLocal(List<SearchAsset> searchAssetList) {
        if (searchAssetList != null) {
            for (SearchAsset asset : searchAssetList) {
                SearchAsset searchAsset = DaoManager.getDaoSession(mContext).getSearchAssetDao().queryBuilder().where(SearchAssetDao.Properties.Id_.eq(asset.getId_())).unique();
                if (searchAsset != null) {
                    continue;
                }
                if (asset.getImgPath() != null && !asset.getImgPath().isEmpty()) {
                    String url = ImageUtils.base64ToFile(asset.getImgPath());
                    if (url != null) {
                        asset.setPictureUri(url);
                    }
                }
                DaoManager.getDaoSession(mContext).getSearchAssetDao().insert(asset);
            }
        }
    }

    public void queryAssetListOnline(String json) {
        try {
            searchView.showProgress("查询中");
            searchService.queryAssetListOnline(json, new Callback() {
                @Override
                public void onFailure(Call call, IOException e) {
                    searchView.onFail(e);
                    mHandler.post(new Runnable() {
                        @Override
                        public void run() {
                            searchView.hideProgress();
                        }
                    });
                }

                @Override
                public void onResponse(Call call, Response response) throws IOException {
                    String json = response.body().string();
                    Result<List<SearchAsset>> result = gson.fromJson(json, new TypeToken<Result<List<SearchAsset>>>() {
                    }.getType());
                    if (result != null && result.getHttpCode() == 200) {
                        final List<SearchAsset> searchAssetList = result.getData();
                        mHandler.post(new Runnable() {
                            @Override
                            public void run() {
                                if (searchAssetList != null) {
                                    searchView.onSuccess(searchAssetList);
                                }
                            }
                        });
                    } else {
                        searchView.onFail(new BusinessErrorException("查询失败"));
                    }
                    mHandler.post(new Runnable() {
                        @Override
                        public void run() {
                            searchView.hideProgress();
                        }
                    });
                }
            });
        } catch (Exception e) {
            e.printStackTrace();
            searchView.onFail(new BusinessErrorException("查询失败"));
            mHandler.post(new Runnable() {
                @Override
                public void run() {
                    searchView.hideProgress();
                }
            });
        }
    }

    // 查询通过扫码
    public void queryByScan(String value) {
        // 1.自动 2.离线
        SyncTypes syncType = DaoManager.getDaoSession(mContext).getSyncTypesDao()
                .queryBuilder().where(SyncTypesDao.Properties.IsSelected.eq(true)).unique();
        int tp = 0;
        if (syncType != null) {
            tp = syncType.getSyscTs();
        }

        if (tp == 1) {
            Map<String, Object> params = new HashMap<>();
            params.put("scan", value);
            params.put("pageNum", 1);
            params.put("pageSize", 999999);
            String json = gson.toJson(params);
            queryAssetListOnline(json);
        } else {
            List<SearchAsset> searchAssetList = DaoManager.getDaoSession(mContext).
                    getSearchAssetDao().queryBuilder().whereOr(
                    SearchAssetDao.Properties.SerialNo.eq(value),
                    SearchAssetDao.Properties.RfidNo.eq(value)).list();
            if (searchAssetList != null) {
                searchView.onSuccess(searchAssetList);
            }
        }
    }

    public void queryByInput() {
        // 1.自动 2.离线
        SyncTypes syncType = DaoManager.getDaoSession(mContext).getSyncTypesDao()
                .queryBuilder().where(SyncTypesDao.Properties.IsSelected.eq(true)).unique();
        int tp = 0;
        if (syncType != null) {
            tp = syncType.getSyscTs();
        }
        if (tp == 1) {
            Map<String, Object> params = new HashMap<>();
            params.put("pageNum", 1);
            params.put("pageSize", 999999);
            if (searchView.getAssetNameText() != null && !searchView.getAssetNameText().isEmpty()) {
                params.put("assetName", searchView.getAssetNameText());
            }
            if (searchView.getAssetNoText() != null && !searchView.getAssetNoText().isEmpty()) {
                params.put("serialNo", searchView.getAssetNoText());
            }
            if (searchView.getRfidText() != null && !searchView.getRfidText().isEmpty()) {
                params.put("rfidNo", searchView.getRfidText());
            }
            if (searchView.getAssetRoom() != null && !searchView.getAssetRoom().isEmpty()) {
                params.put("roomId", searchView.getAssetRoom());
            }
            if (searchView.getAssetStatus() != 0) {
                params.put("status", searchView.getAssetStatus());
            }
            if (searchView.getAssetType() != null && !searchView.getAssetType().isEmpty()) {
                params.put("typeId", searchView.getAssetType());
            }
            String json = gson.toJson(params);
            queryAssetListOnline(json);
        } else {
            QueryBuilder<SearchAsset> qb = DaoManager.getDaoSession(mContext).getSearchAssetDao().queryBuilder();
            if (searchView.getAssetNameText() != null && !searchView.getAssetNameText().isEmpty()) {
                qb.where(SearchAssetDao.Properties.AssetName.like("%" + searchView.getAssetNameText() + "%"));
            }
            if (searchView.getAssetNoText() != null && !searchView.getAssetNoText().isEmpty()) {
                qb.where(SearchAssetDao.Properties.AssetNo.eq(searchView.getAssetNoText()));
            }
            if (searchView.getRfidText() != null && !searchView.getRfidText().isEmpty()) {
                qb.where(SearchAssetDao.Properties.RfidNo.eq(searchView.getRfidText()));
            }
            if (searchView.getAssetRoom() != null && !searchView.getAssetRoom().isEmpty()) {
                qb.where(SearchAssetDao.Properties.RoomId_.eq(searchView.getAssetRoom()));
            }
            if (searchView.getAssetStatus() != 0) {
                qb.where(SearchAssetDao.Properties.Status.eq(searchView.getAssetStatus()));
            }
            if (searchView.getAssetType() != null && !searchView.getAssetType().isEmpty()) {
                qb.where(SearchAssetDao.Properties.TypeId_.eq(searchView.getAssetType()));
            }
            List<SearchAsset> searchAssetList = qb.list();
            if (searchAssetList != null) {
                searchView.onSuccess(searchAssetList);
            }
        }
    }

    public List<Type> queryTypeList() {
        List<Type> typeList = new ArrayList<>();
        Type type = new Type();
        type.setId_("");
        type.setName("请选择类型");
        typeList.add(type);

        List<Type> types = DaoManager.getDaoSession(mContext).getTypeDao().loadAll();
        if (types != null && types.size() > 0) {
            typeList.addAll(types);
        }
        return typeList;
    }

    public List<Status> queryStatusList() {
        List<Status> statusList = new ArrayList<>();
        final Status status = new Status();
        status.setId(0);
        status.setName("请选择状态");
        statusList.add(status);
        Status status1 = new Status();
        status1.setId(1);
        status1.setName("在库");
        statusList.add(status1);
        Status status2 = new Status();
        status2.setId(2);
        status2.setName("已上架");
        statusList.add(status2);
        Status status3 = new Status();
        status3.setId(3);
        status3.setName("已报废");
        statusList.add(status3);
        Status status5 = new Status();
        status5.setId(5);
        status5.setName("待验收");
        statusList.add(status5);
        Status status6 = new Status();
        status6.setId(6);
        status6.setName("使用中");
        statusList.add(status6);
        return statusList;
    }

    public List<Room> queryRoomList() {
        List<Room> roomList = new ArrayList<>();
        Room room = new Room();
        room.setId_("");
        room.setName("请选择地点");
        roomList.add(room);
        List<Room> rooms = DaoManager.getDaoSession(mContext).getRoomDao().loadAll();
        if (rooms != null && rooms.size() > 0) {
            roomList.addAll(rooms);
        }
        return roomList;
    }
}
